package jsonutils

import (
	"encoding/json"
	"fmt"
	jsoniter "github.com/json-iterator/go"
	"github.com/sirupsen/logrus"
)

type JsonUtils struct {
}

func ToJson(v interface{}) (string, error) {
	result, err := jsoniter.Marshal(v)
	if err != nil {
		logrus.Error(err)
		return "{}", err
	}
	return string(result), nil
}

func FromJson(str string, out interface{}) error {

	err := jsoniter.UnmarshalFromString(str, out)
	if err != nil {
		logrus.Error(err)
	}
	return err
}
func ToJsonStr(v interface{}) string {
	result, err := json.Marshal(v)
	if err != nil {
		fmt.Println(err)
		return "{}"
	}
	return string(result)
}
func FromJsonByte(str []byte, anyout interface{}) error {

	err := jsoniter.Unmarshal(str, anyout)
	if err != nil {
		logrus.Error(err)
	}
	fmt.Println("a=", anyout)
	return err
}
func ToJsonPretty(v interface{}) string {
	result, err := json.MarshalIndent(v, " ", "    ")
	if err != nil {
		logrus.Error(err)
		return "{}"
	}
	return string(result)
}

func FromJsonStr(param []byte) interface{} {
	var ret interface{}
	_ = json.Unmarshal(param, &ret)
	return ret
}

func MapFromJson(param string) (m *map[string]interface{}, err error) {
	m = &map[string]interface{}{}
	err = json.Unmarshal([]byte(param), m)
	return m, err
}

func Str2JsonPretty(txt string) string {
	v := FromJsonStr([]byte(txt))
	return ToJsonPretty(v)
}
func Byte2JsonPretty(b []byte) string {
	v := FromJsonStr(b)
	return ToJsonPretty(v)
}
